package com.multiplay;

import java.io.IOException;
import java.nio.channels.Selector;

import android.net.DhcpInfo;
import android.net.wifi.WifiManager;

public class BaseNetLoop 
{
    protected Object parent;
    protected boolean stop = false;

    protected Selector selector = null;

    protected int ip_address;
    protected int netmask;

    public BaseNetLoop(Object p) throws IOException
    {
        parent = p;
        
        selector = Selector.open();
    }

    public boolean init(WifiManager wifi_mng) throws IOException
    {
        if (!wifi_mng.isWifiEnabled())
            return false;
        
        DhcpInfo dhcp = wifi_mng.getDhcpInfo();
        
        ip_address = dhcp.ipAddress;
        netmask = dhcp.netmask;
        
        return (ip_address != 0) ? true : false;
    }

    public static byte [] ip_addr_int2bytes(int addr)
    {
        byte[] quads = new byte[4];
        for (int i = 0; i < 4; i++)
            quads[i] = (byte) ((addr >> i * 8) & 0xFF);
        
        return quads;
    }

    public synchronized void stop_loop()
    {
        stop = true;
        if (selector != null)
            selector.wakeup();
    }

    protected synchronized boolean is_stopping()
    {
        return stop;
    }
}
